import React from 'react';
import { message } from 'antd';
import { createPortal } from 'react-dom';
import { request } from '@/utils/request';
import { useI18n, toApiLanguageCode } from '@/utils/in18';
import { isMobile } from '@/utils/deviceDetection';
import bgvideo from '@/assets/login/heartcloudsmall7.webm'

// 简单的全局事件名，用于从任意位置唤起登录弹窗
const OPEN_EVENT = 'app:open-login';
const AUTH_UPDATED_EVENT = 'auth:updated';

// 对外暴露：调用以打开登录弹窗（支持传入模式）
export function openLoginModal(mode?: Mode) {
    try {
        const ev = new CustomEvent(OPEN_EVENT, { detail: { mode } } as any);
        window.dispatchEvent(ev);
    } catch (e) { }
}

// 保存登录返回后的跳转与页面还原信息（sessionStorage，在本标签页有效）
export function setLoginReturnState(state: any) {
    try {
        const payload = { url: window.location.href, ...state, savedAt: Date.now() };
        sessionStorage.setItem('login:return_state', JSON.stringify(payload));
    } catch { }
}

type Mode = 'login' | 'register';

// 同步游客喜欢
async function syncGuestLikesAfterLogin(authToken: string, userId?: number) {
    try {
        const raw = localStorage.getItem('guestLikedIds');
        if (!raw) return;
        const arr = JSON.parse(raw);
        if (!Array.isArray(arr) || arr.length === 0) return;
        const uniqueIds = Array.from(new Set(arr.filter((x: any) => typeof x === 'number')));
        if (uniqueIds.length === 0) return;
        await request.post(
            '/api/template/likeTemplateRoute',
            { template_id: uniqueIds },
            { headers: { Authorization: authToken } }
        );
        // 同步成功后清空，避免重复上报
        try {
            localStorage.removeItem('guestLikedIds');
            // 同步成功并清空后，向后端请求一次模板列表以刷新用户视图（携带 user_id）
            if (typeof userId === 'number') {
                try {
                    // 根据设备类型选择不同的API接口
                    const apiEndpoint = isMobile()
                        ? '/api/template/getMobileTemplatesRoute'
                        : '/api/template/getTemplatesRoute';
                    await request.post(apiEndpoint, { user_id: userId }, { headers: { Authorization: authToken } });
                } catch { }
            }
        } catch { }
    } catch (e) {
        // 忽略错误，不影响主流程
    }
}

export const LoginModalHost: React.FC = () => {
    const [visible, setVisible] = React.useState(false);
    const [mode, setMode] = React.useState<Mode>('login');
    const [email, setEmail] = React.useState('');
    const [password, setPassword] = React.useState('');
    const [submitting, setSubmitting] = React.useState(false);
    const { locale, t } = useI18n();
    const [showEmailFields, setShowEmailFields] = React.useState(false);
    const [registerPhase, setRegisterPhase] = React.useState<'credentials' | 'verify'>('credentials');
    const [codeDigits, setCodeDigits] = React.useState<string[]>(['', '', '', '', '', '']);
    const otpRefs = React.useRef<Array<HTMLInputElement | null>>([]);
    const [resendLoading, setResendLoading] = React.useState(false);

    // 监听打开登录弹窗
    React.useEffect(() => {
        const onOpen = (ev: any) => {
            const nextMode = ev?.detail?.mode as Mode | undefined;
            if (nextMode === 'login' || nextMode === 'register') setMode(nextMode);
            // 重置显示与输入状态，防止上一次未清空的邮箱/密码导致自动提交
            setShowEmailFields(false);
            setRegisterPhase('credentials');
            setCodeDigits(['', '', '', '', '', '']);
            setEmail('');
            setPassword('');
            setVisible(true);
        };
        window.addEventListener(OPEN_EVENT, onOpen as any);
        return () => window.removeEventListener(OPEN_EVENT, onOpen as any);
    }, []);

    // 关闭登录弹窗
    const onClose = () => {
        if (submitting) return;
        setVisible(false);
    };

    // 统一的登录/注册入口（注册时在输入账号阶段先请求验证码）
    const handleSubmit = async (e?: React.FormEvent) => {
        e?.preventDefault();
        if (submitting) return;
        setSubmitting(true);
        try {
            // 登录：直接走登录接口
            if (mode === 'login') {
                const lang = toApiLanguageCode(locale as any);
                const res = await request.post('/api/auth/loginRoute', { email, password, language: lang });
                if (res.data?.success === true) {
                    await onAuthSuccess(res);
                }
                return;
            }

            // 注册 - 阶段一：请求验证码
            if (mode === 'register' && registerPhase === 'credentials') {
                const langReq = (toApiLanguageCode(locale as any) || '').toUpperCase();
                const payload: any = { email, language: langReq };
                const res = await request.post('/api/auth/requestRegisterCode', payload);
                if (res?.data?.success === true) {
                    setRegisterPhase('verify');
                    // 进入验证码阶段时重置验证码输入
                    setCodeDigits(['', '', '', '', '', '']);
                }
                return;
            }
        } catch (err) {
        } finally {
            setSubmitting(false);
        }
    };

    // 注册 - 阶段二：提交验证码完成注册
    const handleRegisterContinue = async () => {
        if (submitting) return;
        const code = codeDigits.join('').trim();
        if (code.length !== 6) return;
        setSubmitting(true);
        try {
            const lang = mapRegisterRouteLanguage(String(locale || ''));
            const payload: any = { email, password, code };
            if (lang) payload.language = lang;
            const res = await request.post('/api/auth/registerRoute', payload);
            if (res.data?.success === true) {
                await onAuthSuccess(res);
            }
        } catch (err) {
        } finally {
            setSubmitting(false);
        }
    };

    // 复用：登录/注册成功后的本地处理
    const onAuthSuccess = async (res: any) => {
        const email = res.data.data.email;
        const user_token = 'Bearer ' + res.data.token;
        const nickname = res.data.data.nickname;
        const avatar_url = res.data.data.avatar_url;
        const id = res.data.data.id;
        localStorage.setItem('userData', JSON.stringify({ email, user_token, nickname, id, avatar_url }));
        try { localStorage.setItem('token', res.data.token); } catch { }
        setVisible(false);
        // 同步游客喜欢
        try {
            const guestLikedIds = localStorage.getItem('guestLikedIds');
            if (guestLikedIds) {
                const guestLikedIdsArray = JSON.parse(guestLikedIds);
                const uniqueIds = Array.from(new Set(guestLikedIdsArray.filter((x: any) => typeof x === 'number')));
                if (uniqueIds.length > 0) {
                    await syncGuestLikesAfterLogin(user_token);
                }
            }
        } catch { }
        try { window.dispatchEvent(new CustomEvent(AUTH_UPDATED_EVENT)); } catch { }
    };

    // 将本地 locale 映射为注册接口要求的 language 取值
    function mapRegisterRouteLanguage(rawLocale: string): string | undefined {
        const l = rawLocale.toLowerCase();
        if (l.startsWith('es') || l.includes('span')) return 'xby'; // 西班牙语
        if (l.startsWith('fr')) return 'fy'; // 法语
        if (l.startsWith('ja') || l.startsWith('jp')) return 'jp'; // 日语
        if (l.startsWith('en')) return 'en'; // 英语
        if (l.startsWith('ru') || l.includes('rus')) return 'ey'; // 俄语
        return undefined; // 未提供则中文
    }

    // 重新发送验证码
    const handleResendCode = async () => {
        if (submitting || resendLoading) return;
        setResendLoading(true);
        try {
            const langReq = (toApiLanguageCode(locale as any) || '').toUpperCase();
            const res = await request.post('/api/auth/requestRegisterCode', { email, language: langReq });
            if (res?.data?.success === true) {
                try { message.success('Verification code resent.'); } catch { }
            } else {
                try { message.error('Failed to resend code.'); } catch { }
            }
        } catch (err) {
            try { message.error('Failed to resend code.'); } catch { }
        } finally {
            setResendLoading(false);
        }
    };

    // 切换回邮箱输入阶段
    const handleChangeEmail = () => {
        if (submitting) return;
        setRegisterPhase('credentials');
        setShowEmailFields(true);
        setCodeDigits(['', '', '', '', '', '']);
        // 聚焦到邮箱更友好，这里保留简单实现
    };

    // 处理单个验证码输入框变化
    const handleCodeInputChange = (index: number, value: string) => {
        const v = value.slice(-1);
        const next = [...codeDigits];
        next[index] = v;
        setCodeDigits(next);
        if (v && index < 5) {
            otpRefs.current[index + 1]?.focus();
        }
    };

    const handleCodeKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Backspace' && !codeDigits[index] && index > 0) {
            otpRefs.current[index - 1]?.focus();
        }
        if (e.key === 'ArrowLeft' && index > 0) otpRefs.current[index - 1]?.focus();
        if (e.key === 'ArrowRight' && index < 5) otpRefs.current[index + 1]?.focus();
    };

    const handleCodePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
        e.preventDefault();
        const text = e.clipboardData.getData('text').replace(/\s+/g, '');
        if (!text) return;
        const next = text.slice(0, 6).split('');
        const filled = ['', '', '', '', '', ''];
        for (let i = 0; i < next.length && i < 6; i++) filled[i] = next[i];
        setCodeDigits(filled);
        const lastIndex = Math.min(next.length, 6) - 1;
        if (lastIndex >= 0) otpRefs.current[lastIndex]?.focus();
    };

    // Google 登录：从后端获取授权 URL 并跳转
    const handleGoogleLogin = async () => {
        if (submitting) return;
        // 若未预先写入返回状态，这里兜底记录当前地址
        try {
            const existed = sessionStorage.getItem('login:return_state');
            if (!existed) setLoginReturnState({ type: 'routeOnly' });
        } catch { }
        setSubmitting(true);
        try {
            const res = await request.get('/api/google/auth/url');
            const url = res?.data?.data?.url;
            if (res?.data?.success === true && typeof url === 'string' && url.length > 0) {
                try {
                    window.location.href = url;
                } catch {
                    try { window.open(url, '_blank'); } catch { }
                }
            } else {
                // 如果后端没有返回可用 url，则尝试直接打开该接口（后端可返回重定向）
                try { window.location.href = '/api/google/auth/url'; } catch { try { window.open('/api/google/auth/url', '_blank'); } catch { } }
            }
        } catch (e) {
            try { window.location.href = '/api/google/auth/url'; } catch { try { window.open('/api/google/auth/url', '_blank'); } catch { } }
        } finally {
            setSubmitting(false);
        }
    };

    if (!visible) return null;

    const content = (
        // 将根容器 z-index 降低，避免遮挡 Antd 的全局 message（默认 z-index ~1010）
        <div className="fixed inset-0 z-[900]">
            {/* 组件局部 keyframes，用于逆时针旋转 */}
            <style>{`@keyframes spin-reverse { from { transform: rotate(0deg); } to { transform: rotate(-360deg); } }`}</style>

            {/* 蒙版 */}
            <div className="absolute inset-0 bg-black/55 backdrop-blur-[2px]" onClick={onClose} />

            <div className="absolute left-0 right-0 top-1/2 -translate-y-1/2 flex justify-center px-4">

                {/* 内容卡片  */}
                <div className="relative overflow-hidden w-full max-w-md bg-white/90 dark:bg-[#1b1b1b]/100 rounded-2xl shadow-2xl p-6">
                    <video
                        src={bgvideo}
                        autoPlay
                        loop
                        muted
                        playsInline
                        preload="auto"
                        className="absolute inset-0 w-full h-full object-cover pointer-events-none"
                    />
                    {/* 背景蒙版，位于视频之上，内容之下，避免拦截点击 */}
                    <div className="absolute inset-0 bg-black/50 pointer-events-none" />
                    <div className="relative z-10 flex items-start justify-between mb-4">
                        <div className='w-full text-center'>
                            <div className="text-[1.2rem] font-semibold text-[#E5E7EB]">
                                {mode === 'register' && registerPhase === 'verify' ? t('loginModel.enter_confirmation_code') : (mode === 'register' ? t('loginModel.title_sign_up') : t('loginModel.title_welcome_back'))}
                            </div>
                            <div className="text-[0.8rem] font-medium text-[white] mt-1">
                                {mode === 'register' && registerPhase === 'verify'
                                    ? t('loginModel.check_email_for_code').replace('{email}', email)
                                    : t('loginModel.subtitle')}
                            </div>
                        </div>
                        <button onClick={onClose} className="text-[white] -mt-4 -mr-2" aria-label={t('loginModel.close')}>{t('loginModel.close')}</button>
                    </div>
                    {!(mode === 'register' && registerPhase === 'verify') ? (
                        <form onSubmit={handleSubmit} className="relative z-10">
                            {/* Google 登录 */}
                            <button
                                type="button"
                                onClick={handleGoogleLogin}
                                disabled={submitting}
                                className="w-full h-12 rounded-[1rem] bg-white text-gray-900 border border-gray-300 flex items-center justify-center gap-2 shadow-sm hover:shadow transition dark:bg-[#222] dark:text-gray-100 dark:border-[#333]"
                            >
                                <span className="inline-flex items-center justify-center w-5 h-5">
                                    {/*Google Logo */}
                                    <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3215" width="200" height="200"><path d="M214.101 512c0-32.512 5.547-63.701 15.36-92.928L57.173 290.219A491.861 491.861 0 0 0 4.693 512c0 79.701 18.859 154.88 52.395 221.61l172.203-129.066A290.56 290.56 0 0 1 214.1 512" fill="#FBBC05" p-id="3216"></path><path d="M516.693 216.192c72.107 0 137.259 25.003 188.459 65.963l148.95-145.622C763.348 59.18 646.996 11.392 516.692 11.392c-202.325 0-376.234 113.28-459.52 278.827l172.374 128.853c39.68-118.016 152.832-202.88 287.146-202.88" fill="#EA4335" p-id="3217"></path><path d="M516.693 807.808c-134.357 0-247.509-84.864-287.232-202.88L57.173 733.781c83.243 165.547 257.152 278.827 459.52 278.827 124.843 0 244.054-43.392 333.568-124.757L686.677 764.032c-46.122 28.459-104.234 43.776-170.026 43.776" fill="#34A853" p-id="3218"></path><path d="M1005.397 512c0-29.568-4.693-61.44-11.648-91.008H516.651V614.4h274.602c-13.696 65.963-51.072 116.65-104.533 149.632l163.541 123.819C944.256 802.432 1005.397 675.2 1005.397 512" fill="#4285F4" p-id="3219"></path></svg>
                                </span>
                                <span className="text-[14px] font-medium">{t('loginModel.continue_with_google')}</span>
                            </button>

                            {/* 分隔线 */}
                            <div className="flex items-center gap-3 my-4">
                                <div className="flex-1 h-[0.15rem] bg-[#9c9c9c]" />
                                <div className="text-[1rem] font-bold text-[#9c9c9c]">{t('loginModel.or')}</div>
                                <div className="flex-1 h-[0.15rem] bg-[#9c9c9c]" />
                            </div>

                            {/* 邮箱/密码输入（点击后出现） */}
                            {showEmailFields && (
                                <div className="mb-3">
                                    <input
                                        type="email"
                                        style={{ border: "0.2rem solid #b5b5b5" }}
                                        className="w-full px-3 py-3 mb-3 rounded-[1rem] bg-[#ffffff20] text-[#b5b5b5] focus:outline-none focus:ring-0 focus:border-[#b5b5b5]"
                                        placeholder={t('loginModel.email_placeholder')}
                                        value={email}
                                        onChange={(e) => setEmail(e.target.value)}
                                        required
                                        disabled={submitting}
                                    />
                                    <input
                                        type="password"
                                        style={{ border: "0.2rem solid #b5b5b5" }}
                                        className="w-full px-3 py-3 mb-3 rounded-[1rem] bg-[#ffffff20] text-[#b5b5b5] focus:outline-none focus:ring-0 focus:border-[#b5b5b5]"
                                        placeholder={t('loginModel.password_placeholder')}
                                        value={password}
                                        onChange={(e) => setPassword(e.target.value)}
                                        required
                                        disabled={submitting}
                                    />
                                </div>
                            )}

                            {/* Continue with email / Continue / 注册 */}
                            <button
                                type={showEmailFields ? 'submit' : 'button'}
                                onClick={() => {
                                    if (!showEmailFields) setShowEmailFields(true);
                                }}
                                className="w-full h-12 text-[0.9rem] rounded-full bg-[#ffffff31] text-white flex items-center justify-center gap-2 hover:bg-[#ffffff22] transition dark:text-white"
                                disabled={submitting}
                            >
                                {/* 邮箱登录的icon */}
                                <span className="inline-flex text-[#E5E7EB] items-center justify-center w-5 h-5">
                                    <svg viewBox="0 0 1365 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9885" width="200" height="200"><path d="M182.98306 908.65781c5.262221 1.024 10.723553 1.564444 16.298662 1.564444h966.76951c6.399998 0 12.657774-0.711111 18.65955-2.019555l-321.109244-321.137689-95.231974 95.260418a113.493302 113.493302 0 0 1-160.597288-0.085333l-99.185751-99.18575L182.98306 908.65781zM113.777746 816.952946l314.367913-314.367912L114.403524 188.871343A86.044421 86.044421 0 0 0 113.777746 198.997563v617.955383z m1137.777462-2.844443V199.168229l-307.484359 307.484359L1251.555208 814.136947zM200.248833 113.778031l467.797204 467.825647c10.922664 10.894219 29.04177 11.09333 40.106655 0l467.342093-467.313648A86.215087 86.215087 0 0 0 1166.051232 113.778031H200.220389zM0 170.809126A170.723508 170.723508 0 0 1 170.837286 0.000284h1023.658382A170.60973 170.60973 0 0 1 1365.332954 170.809126v682.382033A170.723508 170.723508 0 0 1 1194.495668 1024H170.837286A170.60973 170.60973 0 0 1 0 853.191159V170.809126z" fill="#E5E7EB" p-id="9886"></path></svg>                            </span>
                                <span className="text-[1.1rem] ">
                                    {!showEmailFields ? t('loginModel.continue_with_email') : (mode === 'register' ? t('loginModel.register') : t('loginModel.continue'))}
                                </span>
                            </button>

                            {/* 底部条款 */}
                            <div className="text-[11px] text-[#E5E7EB] mt-4 text-center leading-snug">
                                {t('loginModel.terms_agree')}
                                <a
                                    className="ml-1 underline text-[#E5E7EB]  hover:opacity-80"
                                    href="/Terms"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    onClick={() => window.open('/Terms', '_blank')}
                                >
                                    {t('loginModel.terms_and_conditions')}
                                </a>
                            </div>
                        </form>
                    ) : (
                        <div className="relative z-10">
                            {/* 验证码校验的时候展示的ui  */}
                            <div className="mb-4 flex justify-center gap-2">
                                {codeDigits.map((d, idx) => (
                                    <input
                                        key={idx}
                                        ref={(el) => (otpRefs.current[idx] = el)}
                                        type="text"
                                        inputMode="numeric"
                                        maxLength={1}
                                        value={d}
                                        onChange={(e) => handleCodeInputChange(idx, e.target.value)}
                                        onKeyDown={(e) => handleCodeKeyDown(idx, e as any)}
                                        onPaste={handleCodePaste}
                                        disabled={submitting}
                                        className="w-10 h-12 text-center text-white rounded-md bg-[#ffffff31] border border-[#b5b5b5] focus:outline-none focus:ring-0 focus:border-[#b5b5b5]"
                                    />
                                ))}
                            </div>

                            <button
                                type="button"
                                onClick={handleRegisterContinue}
                                disabled={submitting || codeDigits.join('').length !== 6}
                                className="w-full h-10 rounded-xl  bg-white text-black font-semibold flex items-center justify-center gap-2 hover:opacity-90 transition"
                            >
                                <span className="text-[0.9rem]">{t('loginModel.continue')}</span>
                            </button>

                            {/* 重新发送验证码的按钮和换邮箱地址的按钮  */}
                            <div className="w-full mt-3 flex text-[0.9rem]  items-center font-semibold justify-between">
                                <button
                                    type="button"
                                    onClick={handleResendCode}
                                    disabled={submitting || resendLoading}
                                    className="text-[white] w-[48%]  hover:opacity-80 py-2 rounded-xl flex items-center justify-center gap-1"
                                    style={{ border: '1px solid #E5E7EB' }}
                                >
                                    <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2457" width="18" height="18" style={resendLoading ? { animation: 'spin-reverse 1s linear infinite', transformOrigin: 'center' } : undefined}><path d="M181.731 569.606l63.275-8.713A331.732 331.732 0 0 1 242.255 501l-63.809-2.835a395.86 395.86 0 0 0 3.285 71.441z" fill="#ffffff" p-id="2458"></path><path d="M569.205 906.945c52.791 0 104.019-10.346 152.263-30.752 46.581-19.703 88.409-47.902 124.321-83.814 35.912-35.912 64.111-77.74 83.814-124.322 20.405-48.244 30.752-99.471 30.752-152.263 0-52.791-10.346-104.019-30.752-152.263-19.703-46.581-47.902-88.409-83.814-124.321-35.912-35.912-77.74-64.111-124.321-83.814-48.244-20.405-99.472-30.752-152.263-30.752-101.406 0-197.547 38.644-270.712 108.813-72.938 69.952-115.572 163.96-120.047 264.706L242.255 501c7.783-175.224 151.397-312.483 326.95-312.483 180.462 0 327.278 146.817 327.278 327.278S749.667 843.074 569.205 843.074c-69.625 0-136.091-21.563-192.21-62.357L339.44 832.38c67.106 48.781 146.558 74.565 229.765 74.565z" fill="#ffffff" p-id="2459"></path><path d="M222.367 629.329c8.173 0 16.346-3.118 22.581-9.354l117.233-117.232c12.472-12.471 12.472-32.692 0-45.164-12.471-12.472-32.692-12.472-45.163 0L199.786 574.811c-12.472 12.472-12.472 32.693 0 45.164 6.236 6.236 14.409 9.354 22.581 9.354z" fill="#ffffff" p-id="2460"></path><path d="M215.632 631.398c8.174 0 16.345-3.117 22.581-9.354 12.472-12.471 12.472-32.692 0-45.164L120.981 459.648c-12.47-12.471-32.691-12.471-45.163 0-12.472 12.472-12.472 32.692 0 45.164l117.233 117.232c6.234 6.235 14.409 9.354 22.581 9.354z" fill="#ffffff" p-id="2461"></path></svg>
                                    Resend code
                                </button>
                                <button
                                    type="button"
                                    onClick={handleChangeEmail}
                                    disabled={submitting}
                                    className="text-[#E5E7EB] w-[48%]  hover:opacity-80 py-2 flex items-center justify-center gap-1 rounded-xl"
                                    style={{ border: '1px solid #E5E7EB' }}
                                >
                                    <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3714" width="18" height="18"><path d="M893.842 217.557H130.159c-16.261 0-29.443 13.182-29.443 29.443v530c0 16.261 13.182 29.443 29.443 29.443h763.683c16.261 0 29.443-13.183 29.443-29.443V247c0-16.261-13.182-29.443-29.443-29.443z m-85.584 58.886L512 507.651 215.742 276.443h592.516zM159.602 747.557v-440.23l334.283 260.885A29.4 29.4 0 0 0 512 574.443a29.4 29.4 0 0 0 18.115-6.231l334.283-260.884v440.229H159.602z" fill="#ffffff" p-id="3715"></path></svg>
                                    Change Email
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );

    const host = document.body;
    return host ? createPortal(content, host) : content;
};

export default LoginModalHost;

